package com.yq.order;

import com.google.gson.Gson;
import com.sun.deploy.util.StringUtils;
import com.yq.order.http.RetrofitManager;
import com.yq.order.ocr.OcrPresenter;
import okhttp3.ResponseBody;
import org.jsoup.Jsoup;
import org.jsoup.helper.StringUtil;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by yinqi on 2018/9/1.
 */
public class RequestPresenter {

    public static String COOKIE_PART_ONE = "JSESSIONID=gG2ZbYB0WWx-Lpb7GtubmCp5jj5pQQCJYqWJFxxiZ2xFow2HIUll!2016343238; Hm_lvt_da6f1445af3167cf70ef00845d0e716b=1535726788,1535768409,1535788220; Hm_lpvt_da6f1445af3167cf70ef00845d0e716b=";
    private static String BASE_DIR = "D:\\ems\\pic\\";
    String cookie = COOKIE_PART_ONE + (System.currentTimeMillis() + "").substring(0, 10);
    private OcrPresenter ocrPresenter = new OcrPresenter();
    private Map<String, String> paramsMap = new HashMap<String, String>(2);
    private OcrBean ocrBean;
    private Gson gson = new Gson();

    public void getHtml() {
        // 1535791439 743680
//        String lvpt = COOKIE_PART_ONE + (System.currentTimeMillis() + "").substring(0, 10);
        String lvpt = "JSESSIONID=MhCUHJeIBSjM43-sCuguogb2KYxlE5fs39ruIKjSqPFHsS192MhR!1003117834; Hm_lvt_da6f1445af3167cf70ef00845d0e716b=1535726788,1535768409,1535788220; Hm_lpvt_da6f1445af3167cf70ef00845d0e716b=1535791439";
        Call<String> callString = RetrofitManager.getHttpService().getHtml(cookie);
        callString.enqueue(new Callback<String>() {
            public void onResponse(Call<String> call, Response<String> response) {
                if (response.isSuccessful()) {
                    String body = response.body();
                    System.out.println(body);
                }
            }

            public void onFailure(Call<String> call, Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });
    }

    public void startWork(final String orderNo) {
        try {
            Call<ResponseBody> responseBodyCall = RetrofitManager.getHttpService().downloadCodePic(cookie);
            responseBodyCall.enqueue(new Callback<ResponseBody>() {
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    String name = orderNo + ".jpg";
                    writeResponseBodyToDisk(name, response.body());
                    String result = ocrPresenter.getOcrResult(BASE_DIR + name);
                    ocrBean = gson.fromJson(result, OcrBean.class);
                    String code = ocrBean.getWords_result().get(0).getWords();
                    if (null == code) return;
                    paramsMap.put("mailNum", orderNo);
                    paramsMap.put("checkCode", code);
                    queryOrder(paramsMap);
                }

                public void onFailure(Call<ResponseBody> call, Throwable throwable) {
                    writeLogToFile("exception.txt", orderNo + "network failure" + throwable.getMessage());
                }
            });
        } catch (Exception e) {
            writeLogToFile("exception.txt", orderNo + e.getMessage());
        }
    }

    private void parseHtml(String orderNO, String html) {
        Document document = Jsoup.parse(html, "utf-8");
        if (!document.getElementsByClass("mailnum_box").isEmpty()) {//正确
            Elements mailnum_box = document.getElementsByClass("mailnum_box");
            Elements mailnum_result_box = document.getElementsByClass("mailnum_result_box");
            String result = mailnum_box.get(0).text() + mailnum_result_box.get(0).getAllElements().get(0).text();
            writeLogToFile("right.txt", orderNO + result);
        } else {
            Element singleErrors = document.getElementById("singleErrors");
            writeLogToFile("error.txt", orderNO + singleErrors.text());
        }
    }

    private synchronized void writeLogToFile(String fileName, String result) {
        FileWriter fileWriter = null;
        try {
            File logFile = new File("D:/ems/" + fileName);
            if (!logFile.exists())
                logFile.createNewFile();
            fileWriter = new FileWriter(logFile, true);
            fileWriter.write("\r\n");
            fileWriter.write(result);
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                fileWriter.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 保存下载的图片流写入SD卡文件
     *
     * @param imageName xxx.jpg
     * @param body      image stream
     */
    public static void writeResponseBodyToDisk(String imageName, ResponseBody body) {
        if (body == null) {
            System.out.println("图片源错误");
            return;
        }
        try {
            InputStream is = body.byteStream();
            File fileDr = new File(BASE_DIR);
            if (!fileDr.exists()) {
                fileDr.mkdirs();
            }
            File file = new File(BASE_DIR, imageName);
            if (file.exists()) {
                file.delete();
                file = new File(BASE_DIR, imageName);
            }
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[10 * 1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
            }
            fos.flush();
            fos.close();
            bis.close();
            is.close();
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void queryOrder(final Map<String, String> paramsMap) {
        Call<String> queryCall = RetrofitManager.getHttpService().queryOrder(cookie, paramsMap);
        queryCall.enqueue(new Callback<String>() {
            public void onResponse(Call<String> call, Response<String> response) {
                parseHtml(paramsMap.get("mailNum"), response.body());
            }

            public void onFailure(Call<String> call, Throwable throwable) {
                System.out.println(throwable.getMessage());
            }
        });
    }
}
